import time
import re
from common.pre_config_brower import chrome_brower, request_for_sales
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Grandinroad:
    def __init__(self, url):
        self.driver = chrome_brower(disableIMG=True)
        self.home_url = url
        self.main_windows_id = None
        self.open_web()

    #open the web pages
    def open_web(self):
        try:
            self.driver.get(self.home_url)
            self.main_windows_id = self.driver.window_handles[-1]
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page(self):
        time.sleep(2)
        self.roll_to_top()
        time.sleep(2)
        items_num_info_list = self.driver.find_elements_by_css_selector("[class='item product-item module violated']")
        for item in items_num_info_list:
            produce_url = "https://www.hsn.com" + item.get_attribute("data-product-url")
            img_obj = item.find_element_by_xpath(".//img")
            price_value = item.find_element_by_xpath(".//dl/dd[1]").text
            jpg_name = img_obj.get_attribute('alt')
            jpg_url = img_obj.get_attribute('src')
            if not jpg_url:
                jpg_url = img_obj.get_attribute('data-original')
            yield jpg_url, jpg_name, price_value, produce_url

    def roll_to_top(self):
        js = "var q=document.documentElement.scrollTop=10000"
        self.driver.execute_script(js)